<?php
namespace Modules\Product\Http\Controllers\Admin\V1;

use Illuminate\Http\Request;
use Illuminate\Routing\Controller;

use Modules\Product\Entities\Product;
use Modules\Product\Entities\ProductExt;
use Stbz\Api\SupplyClient;
use Validator;
use ThrowException;
use DB;

class ProductController extends Controller
{
    public function statusTotal(Request $req)
    {
        $rule = [
        ];
        Validator::make($req->all(), $rule)->fails() && ThrowException::BadRequest();
        $total = [
            'on_stock' => Product::status('on_stock')->count(),
            'off_stock' => Product::status('off_stock')->count(),
            'sell_out' => Product::status('sell_out')->count(),
            'marked' => Product::status('marked')->count(),
        ];

        return [
            'total' => $total
        ];
    }
    public static function getSupplyProductList(){
        
        $t1 = microtime(true);
        $supplyClient = new SupplyClient('5EAD103672C6BD067A89F75AF998053F183891655452368','941DBE25600BD4BCDF35EF50EE30CD86');
        $param = ['page'=>1, 'limit'=>20, 'source'=>0];//请求参数source来源：来源0为全部来源1云仓2京东6阿里巴巴7天猫
        $method = 'get';//请求方法
        $action = 'v2/GoodsStorage/MyLists';//请求资源名
        $response = $supplyClient->getApiResponse($method,$action,$param);
        $response = json_decode($response,true);
        
        $pages = ceil($response['data']['count'] / 20);
        
        $tempdata = [];
        for($i=1;$i<=$pages;$i++){
            $param['page'] =$i;
            $response = $supplyClient->getApiResponse($method,$action,$param);
            $response = json_decode($response,true);
            // $tempdata[] = $response['data']['list'];
            
            foreach($response['data']['list'] as $item){
                    // if($item['id']==15249819){
                    //     $tempdata[] = self::getSupplyAddProduct($item);
                    //     //  $oldProuctInfo = Product::where('supply_id', $item['id'])->first();
                    //     // $tempdata = self::getSupplyUpdateProduct($oldProuctInfo,$item);
                    //     break;
                    // }
                $oldProuctInfo = Product::where('supply_id', $item['id'])->first();
                if($oldProuctInfo){
                    $tempdata = self::getSupplyUpdateProduct($oldProuctInfo,$item);
                }else{
                    $tempdata = self::getSupplyAddProduct($item); 
                }
                   
                
                
            }
        }
        $t2 = microtime(true);
        
        return $tempdata;
        
    }
    public static function getSupplyAddProduct($data){
        $supplyClient = new SupplyClient('5EAD103672C6BD067A89F75AF998053F183891655452368','941DBE25600BD4BCDF35EF50EE30CD86');
        $param['id']=$data['id'];
        $method = 'get';//请求方法
        $action = 'v2/Goods/Detail';//请求资源名
        $response = $supplyClient->getApiResponse($method,$action,$param);
        $datas = json_decode($response,true)['data'];
        
        $supplierArray = [1=>'自营',2=>'京东',6=>'阿里巴巴',7=>'天猫'];
        $supplierTitle = $supplierArray[$data['source']] ?? "云仓";
            $category_ids = [5];
        $productInfo = [
            'title'                 =>$data['title'],
            'supply_id'             =>$data['id'],
            'search_key'            =>$data['title'],
            'thumb'                 =>$data['cover'],
            'number'                =>'',
            'supplier'              =>$supplierTitle,
            'ean'                   =>'',
            'cost_price'            =>$data['agreement_price'],
            'money_price'           =>$data['guide_price'],
            'line_money_price'      =>$data['market_price'],
            'score_price'           =>0,
            'category_ids'          =>$category_ids,
            'brand_id'              =>0,
            'status'                =>0,
            'tags'                  =>[],
            'is_need_address'       =>1,
            'is_free_carriage'      =>0,
            'carriage_type'         =>0,//0为包邮  1为到付  2为其它运费模板
            'carriage'              =>0,
            'is_offline_useable'    =>1,
            'is_presell'            =>0,
            'presell_mode'          =>0,
            'presell_date'          =>NULL,
            'remark'                =>'',
            
        ];
        
        preg_match_all('/<img[^>]*?src="([^"]*?)"[^>]*?>/i',$datas['description'],$str,PREG_SET_ORDER);
        $imgArr = [];
        foreach ($str as $img){
            $imgArr[] = $img[1];
        }
        $pages = [
            'style'=>[],
            'modules'=>[
                [
                    'type'=>"imageList",
                    'uuid'=> uniqid(),
                    'style'=>[],
                    'images'=>$imgArr,
                ],
            ],
        ];
        $sku_attrs = [];
        $data_specs = $datas['specs'];
        $skus = [];
        $attr_all_array = [];
        foreach($data_specs['names'] as $k=>$vv){
            $key = ['key'=>$vv['name']];
            $aaa = [];
            foreach($data_specs['values'] as $va){
                
                if($vv['id']==$va['spec_name_id']){
                    $aaa[] = $va['name'];
                   
                    $attr_all_array[] = [
                        'pid'=>$vv['id'],
                        'pname'=>$vv['name'],
                        'id'=>$va['id'],
                        'name'=>$va['name'],
                        ];
                    
                }
                
            }
            $key['value'] = $aaa;
            $sku_attrs[] = $key;
        }
        
        foreach($data_specs['options'] as $v){
            $spec_value_names = explode(',',$v['spec_value_names']);
            $spec_value_ids = explode('_',$v['spec_value_ids']);
            $temarray = [];
            foreach($attr_all_array as $v1){
                if($spec_value_ids[0]==$v1['id']){
                    $temarray[] = ['key'=>$v1['pname'],'value'=>$v1['name']];
                }
                if(isset($spec_value_ids[1]) && $spec_value_ids[1]==$v1['id']){
                    $temarray[] = ['key'=>$v1['pname'],'value'=>$v1['name']];
                }
            }
            $attrs = [];
            
            $skus[] = [
              'attrs'=>$temarray,
                'money_price'=>$v['market_price'],
                'stock'=>$v['stock'],
                'status'=>$v['status'],
                'thumb'=>$v['image'],
                'number'=>'',
                'supply_product_id'=>$v['id'],
                'agreement_price'=>$v['agreement_price'],
                'score_price'=>0,
            ];
        }
        
        $extInfo = [
            'uuid' => uniqid(),
            'images' => $datas['covers'],
            'normal_attrs' => [],
            'sku_attrs' => $sku_attrs,
            'page' => $pages,
        ];
        
        // return [$sku_attrs,$skus,$extInfo];
        $skuInfos = $skus;
        foreach ($skuInfos as $key => $sku) {
            $skuInfos[$key]['uuid'] = uniqid();
        }
        
        DB::beginTransaction();

        // 创建商品
        $product = Product::create($productInfo);

        // \Log::error($product->id);
        // exit();

        // 保存商品扩展信息
        // $product->ext()->create($extInfo);

        $extInfo['product_id'] = $product->id;
        ProductExt::create($extInfo);

        // 保存商品sku信息
        $product->skus()->createMany($skuInfos);

        $product->updateCategoryRelation();
        $product->updateSalesAndStock();

        DB::commit();
        return [];
    }
    public static function getSupplyUpdateProduct($oldProuctInfo,$data){
        $supplyClient = new SupplyClient('5EAD103672C6BD067A89F75AF998053F183891655452368','941DBE25600BD4BCDF35EF50EE30CD86');
        $param['id']=$data['id'];
        $method = 'get';//请求方法
        $action = 'v2/Goods/Detail';//请求资源名
        $response = $supplyClient->getApiResponse($method,$action,$param);
        $datas = json_decode($response,true)['data'];
       
        $supplierArray = [1=>'自营',2=>'京东',6=>'阿里巴巴',7=>'天猫'];
            $category_ids = [5];
        $productInfo = [
            'title'                 =>$data['title'],
            'supply_id'             =>$data['id'],
            'search_key'            =>$data['title'],
            'thumb'                 =>$data['cover'],
            'number'                =>'',
            'supplier'              =>$supplierArray[$data['source']],
            'ean'                   =>'',
            'cost_price'            =>$data['agreement_price'],
            'money_price'           =>$data['guide_price'],
            'line_money_price'      =>$data['market_price'],
            'category_ids'          =>$category_ids,
            'brand_id'              =>0,
            // 'status'                =>0,//商品原来信息
            'tags'                  =>[],
            'is_need_address'       =>1,
            'is_free_carriage'      =>0,
            'carriage_type'         =>0,//0为包邮  1为到付  2为其它运费模板
            'carriage'              =>0,
            'carriage_template_id'  =>null,
            'is_offline_useable'    =>1,
            'is_presell'            =>0,
            'presell_mode'          =>0,
            'presell_date'          =>NULL,
            'remark'                =>'',
            'shop_id'               =>null,
            'images' => $datas['covers'],
            'normal_attrs'=>[],
        ];
        
        preg_match_all('/<img[^>]*?src="([^"]*?)"[^>]*?>/i',$datas['description'],$str,PREG_SET_ORDER);
        $imgArr = [];
        foreach ($str as $img){
            $imgArr[] = $img[1];
        }
   
        $productInfo['page'] = [
            'style'=>[],
            'modules'=>[
                [
                    'type'=>"imageList",
                    'uuid'=> uniqid(),
                    'style'=>[],
                    'images'=>$imgArr,
                ],
            ],
        ];
        $sku_attrs = [];
        $data_specs = $datas['specs'];
        $skus = [];
        $attr_all_array = [];
        foreach($data_specs['names'] as $k=>$vv){
            $key = ['key'=>$vv['name']];
            $aaa = [];
            foreach($data_specs['values'] as $va){
                
                if($vv['id']==$va['spec_name_id']){
                    $aaa[] = $va['name'];
                   
                    $attr_all_array[] = [
                        'pid'=>$vv['id'],
                        'pname'=>$vv['name'],
                        'id'=>$va['id'],
                        'name'=>$va['name'],
                        ];
                    
                }
                
            }
            $key['value'] = $aaa;
            $sku_attrs[] = $key;
        }
        foreach($data_specs['options'] as $v){
            $spec_value_names = explode(',',$v['spec_value_names']);
            $spec_value_ids = explode('_',$v['spec_value_ids']);
            $temarray = [];
            foreach($attr_all_array as $v1){
                if($spec_value_ids[0]==$v1['id']){
                    $temarray[] = ['key'=>$v1['pname'],'value'=>$v1['name']];
                }
                if(isset($spec_value_ids[1]) && $spec_value_ids[1]==$v1['id']){
                    $temarray[] = ['key'=>$v1['pname'],'value'=>$v1['name']];
                }
            }
            $attrs = [];
            if(count($temarray)>0){
                $skus[] = [
                  'attrs'=>$temarray,
                    'money_price'=>$v['market_price'],
                    'stock'=>$v['stock'],
                    'status'=>$v['status'],
                    'thumb'=>$v['image'],
                    'number'=>'',
                    'supply_product_id'=>$v['id'],
                    'agreement_price'=>$v['agreement_price'],
                    'score_price'=>0,
                ];
            }
            
        }
        $productInfo['sku_attrs'] = $sku_attrs;
        
        
        $productInfo['skus'] = $skus;
        
       $keyMap = [
                'title',
                'search_key',
                'thumb',
                'number',
                'supplier',
                'money_price',
                'cost_price',
                'ean',
                'category_ids',
                'brand_id',
                'status',
                'tags',
                'is_presell',
                'presell_mode',
                'presell_date',
                'is_need_address',
                'is_free_carriage',
                'carriage_type',
                'carriage',
                'is_offline_useable',
                'remark',
                'image_tag_id',
            ];

            $newProductInfo = [];
            foreach ($productInfo as $key => $value) {
                if (in_array($key, $keyMap)) {
                    $newProductInfo[$key] = $value;
                }
            }
            $item = Product::getEntity([
                
                'uuid' => $oldProuctInfo->uuid,
            ]);
            
            $item->update($newProductInfo);
            
            // 更新 sku 
            // 删除旧sku
            $oldSkuIds = [];
            foreach ($productInfo['skus'] as $sku) {
                $skuInfo = $item->skus()->where('id', $item->id)->where('attrs', $sku['attrs'])->first();
                if($skuInfo){
                  $sku['id'] =$skuInfo->id;   
                }
                if (@$sku['id']) {
                    array_push($oldSkuIds, $sku['id']);
                }
            }
            
            if (count($oldSkuIds) > 0) {
              $item->skus()->whereNotIn('id', $oldSkuIds)->forceDelete();
            }
            else {
                $item->skus()->forceDelete();
            }
            
            // 如有原sku id， 更新原sku，否则创建sku
            foreach ($productInfo['skus'] as $sku) {
                
                if (isset($sku['id']))
                    $item->skus()->where('id', $sku['id'])->first()->update($sku);
                else {
                    $sku['uuid'] = uniqid();
                    $item->skus()->create($sku);
                }
            }

            // 更新ext
            $extInfo = [
                'images' => @$productInfo['images'],
                'normal_attrs' => $productInfo['normal_attrs'],
                'sku_attrs' => $productInfo['sku_attrs'],
                'page' => $productInfo['page']
            ];
            $item->ext->update($extInfo);

            $item->updateCategoryRelation();
            $item->updateSalesAndStock();
        
    }
    
    public function index(Request $req)
    {
        
        
        // self::getSupplyProductList();
        $rule = [
        ];
        Validator::make($req->all(), $rule)->fails() && ThrowException::BadRequest(); 

        $options = $req->all();

        $options['with'] = ['categories', 'image_tag'];
        $options['with_count'] = ['skus', 'group_prices'];

        $options['order_by'] = [
            'list_weight' => 'desc'
        ];

        $options['only'] = [
            'id',
            'uuid',
            'title',
            'search_key',
            'thumb',
            'number',
            'supplier',
            'money_price',
            'score_price',
            'cost_price',
            'supply_id',
            'stock',
            'list_weight',
            'remark',
            'brokerage_money',
            'brokerage_score',
            'second_brokerage_money',
            'second_brokerage_score',
            'reward_money',
            'reward_score',
            'cover_chip_status',
            'image_tag_id',
            'is_presell',
            'presell_mode',
            'marked_at',
            'order_reward',
            'image_tag' => [
                'title',
                'image',
                'location'
            ],
            'categories' => [
                '*' => [
                    'id',
                    'uuid',
                    'title'
                ]
            ],
            'category_ids',
            'skus_count',
            'group_prices_count',
            'sales',
            'status',
            'created_at',
        ];

        $list = Product::getList($options);

        // $list->each(function ($item) {
        //     $item->stat = $item->stats([
        //         'sales'
        //     ]);
        // });
        return $list->generateListResponse();
        $supplyClient = new SupplyClient('5EAD103672C6BD067A89F75AF998053F183891655452368','941DBE25600BD4BCDF35EF50EE30CD86');
        $param['id']=15038702;
        $method = 'get';//请求方法
        $action = 'v2/Goods/Detail';//请求资源名
        $response = $supplyClient->getApiResponse($method,$action,$param);
        $datas = json_decode($response,true)['data'];
        
        return [$list->generateListResponse(),$datas];
    }

    public function show(Request $req, $uuid)
    {
        $builder = Product::where('uuid', $uuid);

        if (strlen($uuid) < 10) {
            $builder = Product::where('id', intval($uuid));
        }

        $item = Product::getEntity([
        	'builder' => $builder,
            'with' => [
                'ext',
                'skus'
            ]
        ]);

        $info = $item->getInfo();

        return [
            'info' => $info
        ];
    }

    public function store(Request $req)
    {
        $rule = [
            'title' => ['required', 'max:50'],
            'thumb' => ['required'],
            'images' => ['array'],
            'skus' => ['required', 'array'],
            'sku_attrs' => ['required', 'array'],
            'status' => ['required']
        ];
        Validator::make($req->all(), $rule)->fails() && ThrowException::BadRequest(); 

        $productInfo = [
            'title' => $req->input('title'),
            'search_key' => $req->input('search_key'),
            'thumb' => $req->input('thumb'),
            'number' => $req->input('number'),
            'cost_price'=>$req->input('cost_price'),
            'supplier' => $req->input('supplier'),
            'ean' => $req->input('ean'),
            'money_price' => $req->input('money_price'),
            'line_money_price' => $req->input('line_money_price'),
            'score_price' => $req->input('score_price'),
            'category_ids' => $req->input('category_ids'),
            'brand_id' => $req->input('brand_id'),
            'status' => $req->input('status'),
            'tags' => $req->input('tags'),
            'is_need_address' => $req->input('is_need_address'),
            'is_free_carriage' => $req->input('is_free_carriage'),
            'carriage_type' => $req->input('carriage_type'),
            'carriage' => $req->input('carriage'),
            'is_offline_useable' => $req->input('is_offline_useable'),
            'is_presell' => $req->input('is_presell'),
            'presell_mode' => $req->input('presell_mode'),
            'presell_date' => $req->input('presell_date'),
            'remark' => $req->input('remark'),
        ];

        $extInfo = [
            'uuid' => uniqid(),
            'images' => $req->input('images'),
            'normal_attrs' => $req->input('normal_attrs'),
            'sku_attrs' => $req->input('sku_attrs'),
            'page' => $req->input('page')
        ];

        $skuInfos = $req->skus;
        foreach ($skuInfos as $key => $sku) {
            $skuInfos[$key]['uuid'] = uniqid();
        }

        DB::beginTransaction();

        // 创建商品
        $product = Product::create($productInfo);

        // \Log::error($product->id);
        // exit();

        // 保存商品扩展信息
        // $product->ext()->create($extInfo);

        $extInfo['product_id'] = $product->id;
        ProductExt::create($extInfo);

        // 保存商品sku信息
        $product->skus()->createMany($skuInfos);

        $product->updateCategoryRelation();
        $product->updateSalesAndStock();

        DB::commit();

        return [
            'id' => $product->id,
            'uuid' => $product->uuid
        ];
    }

    public function update(Request $req, $uuid)
    {
        $rule = [
        ];
        Validator::make($req->all(), $rule)->fails() && ThrowException::BadRequest(); 

        $item = Product::getEntity([
            'uuid' => $uuid
        ]);

        DB::beginTransaction();

        if ($req->type === 'update') {
            $info = $req->input('attributes');
            $item->update($info);

            $item->updateCategoryRelation();
        }
        elseif ($req->type === 'update_all') {
            $info = $req->input('attributes');

            $keyMap = [
                'title',
                'search_key',
                'thumb',
                'number',
                'supplier',
                'money_price',
                'score_price',
                'cost_price',
                'ean',
                'category_ids',
                'brand_id',
                'status',
                'tags',
                'is_presell',
                'presell_mode',
                'presell_date',
                'is_need_address',
                'is_free_carriage',
                'carriage_type',
                'carriage',
                'is_offline_useable',
                'remark',
                'image_tag_id',
            ];

            $productInfo = [];
            foreach ($info as $key => $value) {
                if (in_array($key, $keyMap)) {
                    $productInfo[$key] = $value;
                }
            }

            $item->update($productInfo);

            // 更新 sku 
            // 删除旧sku
            $oldSkuIds = [];
            foreach ($info['skus'] as $sku) {
                if (@$sku['id']) {
                    array_push($oldSkuIds, $sku['id']);
                }
            }

            if (count($oldSkuIds) > 0) {
               $item->skus()->whereNotIn('id', $oldSkuIds)->forceDelete();
            }
            else {
                $item->skus()->forceDelete();
            }

            // 如有原sku id， 更新原sku，否则创建sku
            foreach ($info['skus'] as $sku) {
                if (isset($sku['id']))
                    $item->skus()->where('id', $sku['id'])->first()->update($sku);
                else {
                    $sku['uuid'] = uniqid();
                    $item->skus()->create($sku);
                }
            }

            // 更新ext
            $extInfo = [
                'images' => @$info['images'],
                'normal_attrs' => $info['normal_attrs'],
                'sku_attrs' => $info['sku_attrs'],
                'page' => $info['page']
            ];
            $item->ext->update($extInfo);

            $item->updateCategoryRelation();
            $item->updateSalesAndStock();
        }
        elseif ($req->type === 'put_on' || $req->type === 'put_off') {
            $item->status = $req->type === 'put_on' ? 1 : 0;
            $item->save();
        }
        elseif ($req->type === 'mark') {
            if ($item->marked_at) {
                $item->update([
                    'marked_at' => NULL
                ]);
            }
            else {
                $item->update([
                    'marked_at' => now()
                ]);
            }
        }

        DB::commit();

        return [];
    }


    public function destroy(Request $req, $uuid)
    {
        $rule = [
        ];
        Validator::make($req->all(), $rule)->fails() && ThrowException::BadRequest(); 

        $product = Product::getEntity([
            'uuid' => $uuid
        ]);

        $product->ext->delete();
        $product->skus()->delete();

        $product->delete();

        return [];
    }
}
